package com.jrx.anytxn.param.job.bactchBillCompare.config;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.StringUtils;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.config.BillCompareConfig;
import com.jrx.anytxn.param.config.PathFileConfig;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.entity.TlBillTransDetil;
import com.jrx.anytxn.param.entity.TlBillTransSummary;
import com.jrx.anytxn.param.mapper.ext.ExtTlBillTransDetilMapper;
import com.jrx.anytxn.param.mapper.ext.ExtTlBillTransSummaryMapper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 核心对账-账务文件落地job
 *
 * @author : zcc
 * 2020/11/26
 */
@Configuration
@EnableConfigurationProperties(PathFileConfig.class)
public class BatchBillFileReadConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(BatchBillFileReadConfiguration.class);

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    private IOrganizationTableService organizationTableService;

    @Autowired
    private ISegmentService iSegmentService;

    @Resource
    private ExtTlBillTransSummaryMapper extTlBillTransSummaryMapper;

    @Resource
    private ExtTlBillTransDetilMapper extTlBillTransDetilMapper;

    @Autowired
    private BillCompareConfig billCompareConfig;


    @Bean
    public Job readerBillFileJob() throws IOException {
        return jobBuilderFactory.get("readerBillFileJob")
                .start(readerFKFileStep())
                .next(readerHKFileStep())
                .build();
    }

    @Bean
    public Step readerFKFileStep() throws IOException {
        return stepBuilderFactory.get("readerFKFileStep").tasklet(readerFKFileTasklet()).build();
    }

    @Bean
    public Tasklet readerFKFileTasklet() {
        return (stepContribution, chunkContext) -> {
            //不需要放款对账，直接返回
            if(!Constant.YES_FLAG.equals(billCompareConfig.getCompareFK())){
                return RepeatStatus.FINISHED;
            }
            //放款对账文件读入开始
            TlBillTransSummary tlBillTransSummary = new TlBillTransSummary();
            List<TlBillTransDetil> tlBillTransDetilList = new ArrayList<>();
            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
            String fileDate = DateUtils.format(org.getToday(), "yyyyMMdd");
            String businessDate = DateUtils.format(org.getToday());

            String billFileForFK = billCompareConfig.getFilePath() + File.separator + fileDate + File.separator + org.getTenantId() + File.separator + billCompareConfig.getPayBankId()+ "_"
                    + billCompareConfig.getPayBusinessId() + "_1_T_" + fileDate + ".txt";

            logger.info("放款对账文件读取开始，路径为:{},业务日期为:{}", billFileForFK, businessDate);

            //清除当日对账数据，支持重跑
            extTlBillTransSummaryMapper.deleteByBusDate(org.getToday());
            extTlBillTransDetilMapper.deleteByBusDate(org.getToday());

            File dirFile = new File(billFileForFK);
            if (dirFile.exists()) {
                /* 读入TXT文件 */
                InputStreamReader reader = new InputStreamReader(new FileInputStream(billFileForFK), StandardCharsets.UTF_8); // 建立一个输入流对象reader
                BufferedReader br = new BufferedReader(reader); // 建立一个对象，它把文件内容转成计算机能读懂的语言
                String line = br.readLine();

                if (line == null) {//如果第一行为空
                    return null;
                }else{//第一行为head行，也入库
                    String[] params = null;
                    line = line.trim();
                    if (0 == line.length()) {
                        throw new Exception("存在为空的一行数据");
                    }
                    params = line.split("\\|", -1);
                    tlBillTransSummary.setId(iSegmentService.getId("TlBillTransSummary"));
                    tlBillTransSummary.setBankId(params[0]);
                    tlBillTransSummary.setMerchants(params[1]);
                    tlBillTransSummary.setTransDate(DateUtils.parseDate(params[2], DateUtils.DATE_PATTERN_ANOTHER));
                    tlBillTransSummary.setTotalCount(StringUtils.toInteger(params[3]));
                    tlBillTransSummary.setSuccessCount(StringUtils.toInteger(params[4]));
                    tlBillTransSummary.setTotalAmount(StringUtils.isNotBlank(params[5]) ? new BigDecimal(params[5]) : BigDecimal.ZERO);
                    tlBillTransSummary.setSuccessAmount(StringUtils.isNotBlank(params[6]) ? new BigDecimal(params[6]) : BigDecimal.ZERO);
                    tlBillTransSummary.setFeeAmnt(StringUtils.isNotBlank(params[7]) ? new BigDecimal(params[7]) : BigDecimal.ZERO);
                    tlBillTransSummary.setTenantId(org.getTenantId());
                    tlBillTransSummary.setOrganizationId(org.getOrganizationId());
                    tlBillTransSummary.setTransactionType(Constant.TRANS_TYPE_FK);
                    tlBillTransSummary.setBusinessDate(org.getToday());
                    extTlBillTransSummaryMapper.insertSelective(tlBillTransSummary);
                }
                String[] params = null;
                while ((line = br.readLine()) != null) {
                    line = line.trim();
                    if (0 == line.length()) {
                        throw new Exception("存在为空的一行数据");
                    }
                    if(line.length()==3 && line.contains("END")){//最后一行END 行跳过
                        break;
                    }
                    params = line.split("\\|", -1);
                    TlBillTransDetil tlBillTransDetil = new TlBillTransDetil();
                    tlBillTransDetil.setId(iSegmentService.getId("TlBillTransDetil"));
                    tlBillTransDetil.setTransactionType(Constant.TRANS_TYPE_FK);
                    tlBillTransDetil.setLoanNumber(params[1]);
                    tlBillTransDetil.setPlatformLoanNumber(params[2]);
                    tlBillTransDetil.setMerchantsSendDate(DateUtils.parseDate(params[3]+"0", DateUtils.ALL_DATETIME_PATTERN));
                    tlBillTransDetil.setSysTransTime(DateUtils.parseDate(params[4]+"0", DateUtils.ALL_DATETIME_PATTERN));
                    tlBillTransDetil.setTransactionAmount(new BigDecimal(params[5]));
                    tlBillTransDetil.setPaymentAccount(params[6]);
                    tlBillTransDetil.setTransStatus(params[7]);
                    tlBillTransDetil.setFeeAmt(new BigDecimal(params[8]));
                    tlBillTransDetil.setRefundStatus(params[9]);
                    tlBillTransDetil.setRefundLoanOrder(params[11]);
                    tlBillTransDetil.setCompareFlag(Constant.COMPARE_FLAG_0);
                    tlBillTransDetil.setTenantId(org.getTenantId());
                    tlBillTransDetil.setOrganizationId(org.getOrganizationId());
                    tlBillTransDetil.setBusinessDate(org.getToday());
                    tlBillTransDetilList.add(tlBillTransDetil);
                }
                if(CollectionUtils.isNotEmpty(tlBillTransDetilList)){
                    extTlBillTransDetilMapper.insertbatch(tlBillTransDetilList);
                }


                logger.info("放款对账文件读取结束，路径为:{},业务日期为:{}", billFileForFK, businessDate);
            }
            return RepeatStatus.FINISHED;
        };
    }


    @Bean
    public Step readerHKFileStep() {
        return stepBuilderFactory.get("readerHKFileStep").tasklet(readerHKFileTasklet()).build();
    }

    @Bean
    public Tasklet readerHKFileTasklet() {
        return (stepContribution, chunkContext) -> {
            //不需要还款对账，直接返回
            if(!Constant.YES_FLAG.equals(billCompareConfig.getCompareHK())){
                return RepeatStatus.FINISHED;
            }
            //还款对账文件读入开始
            TlBillTransSummary tlBillTransSummary = new TlBillTransSummary();
            List<TlBillTransDetil> tlBillTransDetilList = new ArrayList<>();
            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
            String fileDate = DateUtils.format(org.getToday(), "yyyyMMdd");
            String businessDate = DateUtils.format(org.getToday());

            String billFileForHK = billCompareConfig.getFilePath() + File.separator + fileDate + File.separator + org.getTenantId() + File.separator + billCompareConfig.getPayBankId() + "_"
                    + billCompareConfig.getPayBusinessId() + "_13_T_" + fileDate + ".txt";
            logger.info("还款对账文件读取开始，路径为:{},业务日期为:{}", billFileForHK, businessDate);

            File dirFile = new File(billFileForHK);
            if (dirFile.exists()) {
                /* 读入TXT文件 */
                InputStreamReader reader = new InputStreamReader(new FileInputStream(billFileForHK), StandardCharsets.UTF_8); // 建立一个输入流对象reader
                BufferedReader br = new BufferedReader(reader); // 建立一个对象，它把文件内容转成计算机能读懂的语言
                String line = br.readLine();

                if (line == null) {//如果第一行为空
                    return null;
                } else {//第一行为head行，也入库
                    String[] params = null;
                    line = line.trim();
                    if (0 == line.length()) {
                        throw new Exception("存在为空的一行数据");
                    }
                    params = line.split("\\|", -1);
                    tlBillTransSummary.setId(iSegmentService.getId("TlBillTransSummary"));
                    tlBillTransSummary.setBankId(params[0]);
                    tlBillTransSummary.setMerchants(params[1]);
                    tlBillTransSummary.setTransDate(DateUtils.parseDate(params[2], DateUtils.DATE_PATTERN_ANOTHER));
                    tlBillTransSummary.setTotalCount(StringUtils.toInteger(params[3]));
                    tlBillTransSummary.setSuccessCount(StringUtils.toInteger(params[4]));
                    tlBillTransSummary.setTotalAmount(StringUtils.isNotBlank(params[5]) ? new BigDecimal(params[5]) : BigDecimal.ZERO);
                    tlBillTransSummary.setSuccessAmount(StringUtils.isNotBlank(params[6]) ? new BigDecimal(params[6]) : BigDecimal.ZERO);
                    tlBillTransSummary.setFeeAmnt(StringUtils.isNotBlank(params[7]) ? new BigDecimal(params[7]) : BigDecimal.ZERO);
                    tlBillTransSummary.setTenantId(org.getTenantId());
                    tlBillTransSummary.setOrganizationId(org.getOrganizationId());
                    tlBillTransSummary.setTransactionType(Constant.TRANS_TYPE_HK);
                    tlBillTransSummary.setBusinessDate(org.getToday());
                    extTlBillTransSummaryMapper.insertSelective(tlBillTransSummary);
                }
                String[] params = null;
                while ((line = br.readLine()) != null) {
                    line = line.trim();
                    if (0 == line.length()) {
                        throw new Exception("存在为空的一行数据");
                    }
                    if (line.length() == 3 && line.contains("END")) {//最后一行END 行跳过
                        break;
                    }
                    params = line.split("\\|",-1);
                    TlBillTransDetil tlBillTransDetil = new TlBillTransDetil();
                    tlBillTransDetil.setId(iSegmentService.getId("TlBillTransDetil"));
                    tlBillTransDetil.setTransactionType(Constant.TRANS_TYPE_HK);
                    tlBillTransDetil.setLoanNumber(params[1]);
                    tlBillTransDetil.setPlatformLoanNumber(params[2]);
                    tlBillTransDetil.setMerchantsSendDate(DateUtils.parseDate(params[3]+"0", DateUtils.ALL_DATETIME_PATTERN));
                    tlBillTransDetil.setSysTransTime(DateUtils.parseDate(params[4]+"0", DateUtils.ALL_DATETIME_PATTERN));
                    tlBillTransDetil.setTransactionAmount(new BigDecimal(params[5]));
                    tlBillTransDetil.setPaymentAccount(params[6]);
                    tlBillTransDetil.setTransStatus(params[7]);
                    tlBillTransDetil.setFeeAmt(new BigDecimal(params[8]));
                    tlBillTransDetil.setRefundStatus(params[9]);
                    tlBillTransDetil.setCompareFlag(Constant.COMPARE_FLAG_0);
                    tlBillTransDetil.setTenantId(org.getTenantId());
                    tlBillTransDetil.setOrganizationId(org.getOrganizationId());
                    tlBillTransDetil.setBusinessDate(org.getToday());
                    tlBillTransDetilList.add(tlBillTransDetil);
                }
                if(CollectionUtils.isNotEmpty(tlBillTransDetilList)){
                    extTlBillTransDetilMapper.insertbatch(tlBillTransDetilList);
                }

                logger.info("还款对账文件读取结束，路径为:{},业务日期为:{}", billFileForHK, businessDate);

            }
            return RepeatStatus.FINISHED;
        };
    }
}